package cn.tworice.admin.web;

import cn.tworice.admin.service.DistValueService;
import cn.tworice.common.entity.code.*;
import cn.tworice.common.inducts.InductsListener;
import cn.tworice.common.vo.*;
import com.alibaba.excel.EasyExcel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;

import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

@RestController
@RequestMapping("/admin/distValue")
@CrossOrigin
public class DistValueClient {
    @Autowired
    private DistValueService service;

    @GetMapping("list")
    @ApiOperation("通过条件查询获取列表")
    public RequestResult list(@ApiParam("页码")
                              Integer page, @ApiParam("每页数量")
                              Integer pageSize, @ApiParam("查询条件")
                              DistValue entity) {
        RequestResult result = new RequestResult();
        result.appendData("list", service.getList(page, pageSize, entity));
        result.appendData("total", service.getTotal(entity));
        return result;
    }

    @PostMapping("add")
    @ApiOperation("新增数据")
    public RequestResult add(DistValue entity) {
        RequestResult result = new RequestResult();
        service.set(entity);
        return result;
    }

    @DeleteMapping("del")
    @ApiOperation("通过ID数组删除数据")
    public RequestResult del(@ApiParam("数据ID数组")
                             Integer[] ids) {
        RequestResult result = new RequestResult();
        service.del(ids);
        return result;
    }

    @PostMapping("inducts")
    @ApiOperation("通过Excel表格批量上传数据")
    public RequestResult inducts(@ApiParam("Excel文件")
                                 MultipartFile file) {
        RequestResult result = new RequestResult();
        try {
            InputStream inputStream = file.getInputStream();
            EasyExcel.read(inputStream, DistValue.class, new InductsListener(service)).sheet().doRead();
            result.setStatus(new StatusCode(200, "批量导入数据成功")
            );
        } catch (Exception ex) {
            ex.printStackTrace();
            result.setStatus(new StatusCode(204, "批量导入数据失败")
            );
        }
        return result;
    }

    @GetMapping("info")
    @ApiOperation("通过ID获取数据")
    public RequestResult info(Integer id) {
        RequestResult result = new RequestResult();
        DistValue info = service.getInfo(id);
        result.appendData("info", info);
        return result;
    }
}